////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   Software       : S-LOGGER                                                //
//   Layer          : SRC                                                     //
//   Package        :                                                         //
//   Component      : S-LOGGER                                                //
//                                                                            //
//   File           : cdisplay.cpp                                            //
//   Author         : RSO ( Rafael Sotomayor Brûlé )                          //
//   EMail          : rsotomayor@savtec.cl                                    //
//   Type           : C++ Source                                              //
//   Usage          :                                                         //
//   Purpose        : Clase para desplegar datos                              //
//                                                                            //
//                                                                            //
//   who when        what                                                     //
//   ~~~ ~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//   RSO 01-01-2008  Creation                                                 //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////


#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>

#include "mylib/errlog.h"
#include "mylib/utilconf.h"
#include "myglobal.h"
#include "curlit.h"
#include "myutil.h"

#include "cconfig.h"
extern CConfig   *config_g;

extern MyGlobal   *global_g;

MyUtil* MyUtil::pMyUtil_a=NULL;

MyUtil::MyUtil() {
  pMyUtil_a = this ; 
  tInicio_a = time(NULL);
} ;

MyUtil::~MyUtil() {

};

void MyUtil::setTimeUp() {
  tUp_a = time(NULL) - tInicio_a ;

}

int MyUtil::wget(const char *url_p,string &response_p) {
  int retval = -1 ;

  errLog::LOGERR((errLog::TRACE,(char *)"URL: %s\n",url_p));
  
  std::string responseok = "SNAM-OK" ;
//  std::string response;
 // cout << curlit::get(url) << endl;  

  try {
    response_p = curlit::get(url_p) ;  
  } catch(...){ 
    return -1;  
  }

//  errLog::LOGERR((errLog::TRACE,(char *)"RESPONSE: [%s] \n",response.data()));  
  
  size_t found;
  found=response_p.find(responseok);
  if (found!=string::npos) {
    retval = 0 ;
  }

  return retval;

 
}

int MyUtil::wpost(const char *url_p,map<string, string> &m,string &response_p) {
  int retval = -1 ;

  errLog::LOGERR((errLog::TRACE,(char *)"URL: %s\n",url_p));
  
  std::string responseok = "CAAC-OK" ;
//  std::string response;
 // cout << curlit::get(url) << endl;  

    try {
      response_p = curlit::post(url_p,m) ;  
    } catch(...){ 
      return -1;  
    }

//  errLog::LOGERR((errLog::TRACE,(char *)"RESPONSE: [%s] \n",response.data()));  
  
  size_t found;
  found=response_p.find(responseok);
  if (found!=string::npos) {
    retval = 0 ;
  }

  return retval;

 
}

int MyUtil::wget(const char *hostname_p,const char *url_p,std::string parameter_p) {
  int retval = -1 ;

  char url[1024];
  
  sprintf(url,"http://%s%s?%s",hostname_p,url_p,parameter_p.data()) ;
  errLog::LOGERR((errLog::TRACE,(char *)"URL: %s\n",url));
  
  std::string responseok = "CAAC-OK" ;
  std::string response;
 // cout << curlit::get(url) << endl;  

  try {
    response = curlit::get(url) ;  
  } catch(...){ 
    return -1;  
  }

//  errLog::LOGERR((errLog::TRACE,(char *)"RESPONSE: [%s] \n",response.data()));  
  
  size_t found;
  found=response.find(responseok);
  if (found!=string::npos) {
    retval = 0 ;
  }

  return retval;

 
}

vector<string> MyUtil::split(const string& strValue, char separator)
{
    vector<string> vecstrResult;
    int startpos=0;
    int endpos=0;

    endpos = strValue.find_first_of(separator, startpos);
    while (endpos != -1)
    {       
        vecstrResult.push_back(strValue.substr(startpos, endpos-startpos)); // add to vector
        startpos = endpos+1; //jump past sep
        endpos = strValue.find_first_of(separator, startpos); // find next
        if(endpos==-1)
        {
            //lastone, so no 2nd param required to go to end of string
            vecstrResult.push_back(strValue.substr(startpos));
        }
    }

    return vecstrResult;
}


void MyUtil::Tokenize(const string& str,
                      vector<string>& tokens,
                      const string& delimiters)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}


string MyUtil::myexec(const char* cmd_p) {
    FILE* pipe = popen(cmd_p, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
                result += buffer;
    }
    pclose(pipe);
    return result;
}  


void MyUtil::find_and_replace( string &source, const string find, string replace ) {
 	size_t j;
	for ( ; (j = source.find( find )) != string::npos ; ) {
		source.replace( j, find.length(), replace );
	}
}  

void MyUtil::checkTemperature() {
#if defined(__arm__) 
  // ts7500ctl --gettemp | awk 'BEGIN { FS="temperature="} ; { nlines++;if ( nlines== 2 ) print $2; };'
  string command,result ;
  command = "ts7500ctl --gettemp | awk 'BEGIN { FS=\"temperature=\"} ; { nlines++;if ( nlines== 2 ) print $2; };'";
  result = this->myexec(command.data());
  find_and_replace(result,"\n","");
  find_and_replace(result,"\r","");
  temperature_a = result;
#else
  temperature_a = "NA";
#endif

}

int MyUtil::getMyIpAddress(const char *dev_p,string &ipaddress_p) {
  int fd;
  struct ifreq ifr;

  fd = socket(AF_INET, SOCK_DGRAM, 0);

  /* I want to get an IPv4 IP address */
  ifr.ifr_addr.sa_family = AF_INET;

  /* I want IP address attached to "eth0" */
  strncpy(ifr.ifr_name, dev_p, IFNAMSIZ-1);

  ioctl(fd, SIOCGIFADDR, &ifr);

  close(fd);

  char ipaddress[128];

  strcpy(ipaddress, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
  ipaddress_p = ipaddress ;

  return 0;
}

bool MyUtil::FileExists(const char *path) 
{
  	struct 	stat st;
  	bool 	blnReturn;
  	int 	intStat;
	if(stat(path, &st) == 0)
  	{
		blnReturn = true;
  	} 
  	else 
  	{	
  		blnReturn = false;
  	}
  
  	return(blnReturn);
}

